/**
* Copyright 2012 nabla
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
package com.nabla.wapp.client.ui;

import com.nabla.wapp.client.general.Assert;
import com.nabla.wapp.shared.general.Nullable;
import com.nabla.wapp.shared.signal.Signal1;
import com.nabla.wapp.shared.slot.ISlot;
import com.nabla.wapp.shared.slot.ISlotManager1;


public class WizardClientArea extends VLayout {

	private IWizardNavigationCommandSet		navigation;
	private final WizardPageStack			pages = new WizardPageStack();
	private boolean						enabled = true;
	private final Signal1<IWizardPage>		sigPageChanged = new Signal1<IWizardPage>();

	public void setNavigation(final IWizardNavigationCommandSet navigation) {
		this.navigation = navigation;
		navigation.previous().connect(new ISlot() {
			@Override
			public void invoke() {
				if (enabled)
					displayPage(pages.pop(), pages.top());
			}
		});
		navigation.next().connect(onNextClicked);
		navigation.finish().connect(onNextClicked);
	}

	public void unbind() {
		pages.clear();
	}

	public void setNavigationEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void displayNextPage(final IWizardPage nextPage) {
		final IWizardPage oldPage = pages.top();
		pages.push(nextPage);
		displayPage(oldPage, nextPage);
	}

	public void displayErroneousPage() {
		if (!pages.isEmpty()) {
			final IWizardPage currentPage = pages.top();
			if (!currentPage.hasErrors())
				displayPage(currentPage, pages.popToFirstErroneousPage());
		}
	}

	public ISlotManager1<IWizardPage> getPageChangedSlots() {
		return sigPageChanged;
	}

	private void displayPage(@Nullable final IWizardPage oldPage, final IWizardPage newPage) {
		if (oldPage != null)
			removeMember(oldPage.getImpl());
		addMember(newPage.getImpl());
		sigPageChanged.fire(newPage);
		setNavigationEnabled(true);
		navigation.previous().setVisible(pages.size() > 1 && newPage.getNextButton() != WizardPageNavigations.COMPLETED);
		navigation.next().setVisible(WizardPageNavigations.NEXT == newPage.getNextButton());
		navigation.finish().setVisible(WizardPageNavigations.FINISH == newPage.getNextButton());
	}

	private final ISlot onNextClicked = new ISlot() {
		@Override
		public void invoke() {
			if (enabled) {
				final IWizardPage page = pages.top();
				Assert.notNull(page);
				if (page.validate()) {
					setNavigationEnabled(false);
					page.onNextClicked();
				}
			}
		}
	};

}
